package Map
{
	import flash.display.Sprite;
	
	public class CMap
	{
		private var m_sprite :Sprite;
		private var m_arrMapTile :Array;
		private var m_nMapSizeX :uint;
		private var m_nMapSizeY :uint;
		
		public function get sprite() :Sprite { return m_sprite; }
		public function get nMapSizeX() :uint { return m_nMapSizeX; }
		public function get nMapSizeY() :uint { return m_nMapSizeY; }
		
		public function CMap()
		{
			m_sprite = new Sprite();
			m_arrMapTile = new Array();
		}
		public function Init(refMapData :CMapData) :Boolean
		{
			if (refMapData == null || refMapData.nMapSizeX == 0 || refMapData.nMapSizeY == 0)
			{
				trace("Failed! CMap:Init(), Invalidate Argument");
				return false;
			}
			
			for (var iRow :uint = 0; iRow < refMapData.nMapSizeY; ++iRow)
			{
				var arrMapTileRow :Array = new Array();
				for (var iCol :uint = 0; iCol < refMapData.nMapSizeX; ++iCol)
				{
					var nMapType :uint = refMapData.GetMapTileType(iCol, iRow);
					var cMapTile :CMapTile = CreateMapTile(nMapType, iCol, iRow);
					if (cMapTile == null)
					{
						trace("Failed! CMap:Init(), CreateMapTile() is return null");
						return false;
					}
					
					arrMapTileRow.push(cMapTile);
					cMapTile.AddToParent(this.sprite);
				}
				m_arrMapTile.push(arrMapTileRow);
			}
			
			m_nMapSizeX = refMapData.nMapSizeX;
			m_nMapSizeY = refMapData.nMapSizeY;
			
			return true;
		}
		public function GetMapTile(nMapPosX :int, nMapPosY :int) :CMapTile
		{
			if (m_arrMapTile[nMapPosY] == null) return null;
			return m_arrMapTile[nMapPosY][nMapPosX];
		}
		public function Clear() :void
		{
			for (var iRow :uint = 0; iRow < m_arrMapTile.length; ++iRow)
			{
				var arrMapTileRow :Array = m_arrMapTile[iRow] as Array;
				for (var iCol :uint = 0; iCol < arrMapTileRow.length; ++iCol)
				{
					var cMapTile :CMapTile = arrMapTileRow[iCol];
					cMapTile.RemoveFromParent(this.sprite);
					
					arrMapTileRow[iCol] = null;
				}
				arrMapTileRow.splice(0, arrMapTileRow.length);
				m_arrMapTile[iRow] = null;
			}
			m_arrMapTile.splice(0, m_arrMapTile.length);
		}
		private function CreateMapTile(nType :uint, iCol :int, iRow :int) :CMapTile
		{
			switch(nType)
			{
			case CMapTile.TYPE_NORMAL:	return new CMapTile_Normal(iCol, iRow);
			case CMapTile.TYPE_BLOCK:	return new CMapTile_Block(iCol, iRow);
			case CMapTile.TYPE_DOOR:	return new CMapTile_Door(iCol, iRow);
			case CMapTile.TYPE_GOAL:	return new CMapTile_Goal(iCol, iRow);
			}
			return null; 
		}
		
	}
}